<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

class PublicAction extends Action {
	// 检查用户是否登录

	protected function checkUser() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->assign('jumpUrl','Public/login');
			$this->error('没有登录');
		}
	}

	// 顶部页面
	public function top() {
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$model	=	D("function");
		$list	=	$model->where(' pid = 0')->select();
		$in     =   $this->filterFunction($list);
		foreach($list as $key => $val){
			     if(in_array($val['id'],$in)){
					        $topFun[] = $val; 
					 }
			}
		$this->assign('nodeGroupList',$topFun);
		$this->display();
	}
	
	/*+---------------------------------------------
	  |    功能过滤
	  +---------------------------------------------
	  */
	public function filterFunction($Fids){
		   foreach($Fids as $key => $val){
			     $FidArray[] = $val['id'];   
		   }
	       $in = array_intersect($FidArray,$_SESSION[C('FUNCTION_KEY')]);
		   return $in;
	}
	// 尾部页面
	public function footer() {
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$this->display();
	}
	// 菜单页面
	public function menu(){
        if($_GET['tag']){
            if($_SESSION[C('USER_TYPE')] == "1"){
			    if($_GET['tag'] == "59"){         
				    //获取站点信息
				    $menu=$this->getWebsiteInfo(); 
					$this->showWebsiteList($_GET['title'],$menu);
					
			    }else{

					$menu=$this->get_menu($_GET['tag']);   //获取功能信息
					$this->showMenuList($_GET['title'],$menu);
				}
            }
			
        }else{
            if($_SESSION[C('USER_TYPE')] == "0"){
                $menu=$this->get_menu(136);
                $_GET['title'] = "功能列表";
				$this->showMenuList($_GET['title'],$menu);
            } 
		}
		if($_GET['wid']){
			  $in_array = $this->getWebsiteFunction($_GET['wid']);
			  //echo "<pre>";print_r($in_array);exit;
			  $menu = $this->get_menu(136,$in_array);
			  $this->showMenuList("功能列表",$menu);
	    }
		
		
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$this->display();
	}
	
	/*+---------------------------------------------------------+
	  |     默认显示菜单列表                                      |
	  +---------------------------------------------------------+*/
	public function showMenuList($title,$menu){
	    echo '<div id="menu" class="menu" style="width:200px;height:85%" >';
		echo '<div class="tCenter space" style="border:1px solid #ccc;width:200px;height:30px;line-height:30px;">';
		echo '<img SRC="'.__ROOT__.'/Public/images/home.gif" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" valign="middle" style="margin-right:5px;">';
		echo $title?$title:"后台首页";
        echo '</div>';
        echo "<div style='width:200px;height:100%;margin-top:5px;'>";
		echo '<div id="treeboxbox_tree" setImagePath="'.__ROOT__.'/Public/Js/menuTree/csh_bluebooks/" class="dhtmlxTree" style="width:100%;height:100%; background-color:#f5f5f5;border :1px solid Silver; text-align:left">';
		echo $menu;
		echo "</div>";
		echo "</div>";
		echo "</div>";  	
	}
	
	/*+---------------------------------------------------------+
	  |     站点列表                                             |
	  +---------------------------------------------------------+*/
	public function showWebsiteList($title,$menu){
		echo '<div id="menu" class="menu" style="width:200px;height:85%" >';
		echo '<div class="tCenter space" style="border:1px solid #ccc;width:200px;height:30px;line-height:30px;">';
		echo '<img SRC="'.__ROOT__.'/Public/images/home.gif" WIDTH="16" HEIGHT="16" BORDER="0" ALT="" valign="middle" style="margin-right:5px;">';
		echo $title?$title:"后台首页";
        echo '</div>';
        echo "<div style='width:200px;height:100%;margin-top:5px;'>";
		echo '<div style="width:100%;height:100%; background-color:#f5f5f5;border :1px solid Silver; text-align:left">';
		echo $menu;
		echo "</div>";
		echo "</div>";
		echo "</div>";
	}
	/*+---------------------------------------------------------
	  |     获取功能有序列表
	  +---------------------------------------------------------
	  |     @param => pid =>某级分类的父ID
	  +---------------------------------------------------------
	  */
    public function get_menu($pid,$function){
		if($function){
		      $addition['in_array'] = $function;
	    }else{
        	  $addition['in_array'] = $_SESSION[C("FUNCTION_KEY")];
		}
	    $pos=D("function");
		$show_list=$pos->where("pid = {$pid}")->select();
		$pro_menu="<ul>";
		$pro_menu.=$this->digui($show_list,$addition);   //无限分类，递归调用
		$pro_menu.="</ul>";	
		return $pro_menu;
	}
    
	/*+---------------------------------------------------------
	  |     递归调用，判断是否还有子类别，将所有子类别，查询出来
	  +---------------------------------------------------------
	  |     @param => list => 当前级分类的查询结果
	  +---------------------------------------------------------*/
	public function digui($list,$addition){
        $pos=D("function");
        foreach($list as $key=>$val){
            if(in_array($val['id'],$addition['in_array'])){
			     $pro_menu.="<li>";
                 if($val['function_entry'] != ""){
				      $pro_menu.="<a target='main' href='".__ROOT__."/";
				      $pro_menu.=$val['function_entry']."/";
					  if($val['function_act'] !=""){
					  		$pro_menu.=$val['function_act']."/";
						}
					  if($val['function_app'] != ""){
				      		$pro_menu.=$val['function_app']."/";
					  }
					  if($val['id'] != ""){
				      		$pro_menu.="Fid/".$val['id']."/";
					  }
                      $pro_menu.="'>";
                          $pro_menu .=$val["function_title"];
                      $pro_menu.="</a>";
                 }else{
                      $pro_menu .=$val["function_title"];
                 }
                 $show_list=$pos->where("pid=".$val["id"])->select();
			     if(count($show_list)>0){
			            $pro_menu.="<ul>";
			            $pro_menu.=$this->digui($show_list,$addition);
			            $pro_menu.="</ul></li>";
			     }else{
			            $pro_menu.="</li>";
			     }
            }
      
        }
        return $pro_menu;
	}

    /*+-----------------------------------------------+
	  |    获取站点信息                                 |
	  +-----------------------------------------------+*/
	public function getWebsiteInfo(){
	        $website = D("website");
			$web     = $website ->select();
			foreach($web as  $key => $val){
				    $menu .= "<span style='border:1px solid #ccc;display:block;height:25px;margin:3px 3px 3px 3px;padding:3px 3px 3px 3px;'><a href='".__ROOT__."/Website/".$val['database']."' target='_blank'>预览</a>&nbsp;&nbsp;<a href='".U("Public/menu/wid/".$val['id'])."' target='menu' >".$val['website_name']."</a></span>";	 
			}
			return $menu;
			
    }
	
	/*+-----------------------------------------------+
	  |     切换数据库，显示该站点的信息                  |
	  +-----------------------------------------------+*/
	public function getWebsiteFunction($id){
			$website   = D("website");
            $database  = $website -> field("database")->where("id = {$id}")->find();
            //将该站点的数据库名称存入session中
            $_SESSION[C("DATA_KEY")] = $database['database'];
	        $changeDB  = new Model();      //切换到子站数据库
			$changeDB  ->query("use {$database['database']}");
			$group  = D("group");
			$function = $group->field("group_function")->where("id = 1")->find();
			$funcId = explode(",",$function['group_function']);
			//将数据库切回；
			$changeDB ->query("use dhjdsj_douhaosystem");
			return $funcId;
			//print_r($funcId);
			//exit;
    }
	
    // 后台首页 查看系统信息
    public function main() {
		$model	=	D("function");
		$list	=	$model->where(' pid = 0')->select();
		//$in     =   $this->filterFunction($list);
        //echo "<pre>";
        //print_r($in);
        
        //echo $_SERVER['DOCUMENT_ROOT'].__ROOT__."/DefineWebsiteDatabase/database.sql";
        //echo "<pre>";
        //print_r($_SESSION);
        $this->display();
    }

	// 用户登录页面
	public function login() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			//echo C ( 'RBAC_ERROR_PAGE' );
			//secho C ( 'GUEST_AUTH_ON' )
			$this->display();
		}else{
			$this->redirect('Index/index');
		}
	}

	public function index()
	{
		//如果通过认证跳转到首页
		redirect(__APP__);
	}

	// 用户登出
    public function logout()
    {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();
            $this->assign("jumpUrl",__URL__.'/login/');
            $this->success('登出成功！');
        }else {
			$this->assign("jumpUrl",__URL__.'/login/');
            $this->error('已经登出！');
        }
    }

	// 登录检测
	public function checkLogin() {
		if(empty($_POST['account'])) {
			$this->error('帐号错误！');
		}elseif (empty($_POST['password'])){
			$this->error('密码必须！');
		}elseif (empty($_POST['verify'])){
			$this->error('验证码必须！');
		}
        //生成认证条件
        $map            =   array();
		// 支持使用绑定帐号登录
		$map['sysuser_name']	= $_POST['account'];
        $map["status"]	=	array('eq',"1");
		if($_SESSION['verify'] != md5($_POST['verify'])) {
			$this->error('验证码错误！');
		}
		import ( '@.ORG.RBAC' );
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if($authInfo === null) {
            $this->error('帐号不存在或已禁用！');
        }else {
            if($authInfo['sysuser_password'] != md5($_POST['password'])) {
            	$this->error('密码错误！');
            }
            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
            $_SESSION['email']	            =	$authInfo['sysuser_email'];
            $_SESSION['loginUserName']		=	$authInfo['sysuser_nikename'];
            $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
            $_SESSION['login_count']	    =	$authInfo['login_count'];
            $_SESSION[C('FUNCTION_KEY')]    =   $authInfo['group_function'];
            $_SESSION[C('USER_TYPE')]       =   $authInfo['user_type'];
			$_SESSION[C('DATA_KEY')]        =   $authInfo['database'];
			$_SESSION['wid']	            =	$authInfo['Wid']; //站点id
            if($authInfo['sysuser_name']    ==  'admin'){
            	$_SESSION['administrator']	=	true;
            }
            //保存登录信息
			$User	=	M('sysuser');
			$ip		=	get_client_ip();
            $data = array();
			$data['id']              =	$authInfo['id'];
			$data['last_login_time'] =	toDate(time());
			$data['login_count']	 =	array('exp','login_count+1');
			$data['last_login_ip']	 =	$ip;
			$User->save($data);

			// 缓存访问权限
            RBAC::saveAccessList();
			$this->success('登录成功！');

		}
	}
    // 更换密码
    public function changePwd()
    {
		$this->checkUser();
		$this->assign('jumpUrl',__URL__.'/password');
        //对表单提交处理进行处理或者增加非表单数据
		if(md5($_POST['verify'])	!= $_SESSION['verify']) {
			$this->error('验证码错误！');
		}
        $oldpwd= md5(trim($_POST['oldpassword']));
        //检查用户
        $map['id'] = intval($_SESSION['authId']);
        $User    =   D("sysuser");
        $userInfo = $User->where($map)->field('user_type,sysuser_password,`database`')->find();
        if(!$userInfo || $userInfo['sysuser_password']!=$oldpwd) {
            $this->error('旧密码填写不正确！');
        }else {
			$data['sysuser_password']	=	md5(trim($_POST['password']));
			$User->where($map)->save($data);
			if($userInfo['user_type']==0)
			{
				//切换数据库 修改密码
				$User->query("use ".$userInfo['database']);
				$model    =   new Model();
				$model->query("update douhao_sysuser set sysuser_password = '{$data['sysuser_password']}'");
			}
			$this->success('密码修改成功！');
         }
    }
	public function profile() {
		$this->checkUser();
		$User	 =	 M("sysuser");
		$vo	=	$User->getById($_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('vo',$vo);
		$this->display();
	}
	 public function verify()
    {
		$type	 =	 isset($_GET['type'])?$_GET['type']:'gif';
        import("@.ORG.Image");
        Image::buildImageVerify(4,1,$type);
    }
    //修改资料
	public function changeProfile() {
		$this->checkUser();
		$User	 =	 D("sysuser");
		if(!$User->create()) {
			$this->error($User->getError());
		}
		$User->update_time = date('Y-m-d H:i:s');
		$result	=	$User->save();
		if(false !== $result) {
			//修改站点用户信息
			$database = $_SESSION[C('DATA_KEY')];
			if(!empty($database))
			{
				//C('DB_NAME',$database);
				$User->query("use ".$database);
				$User	 =	 D("sysuser");
				$data['sysuser_nikename'] = trim($_POST['sysuser_nikename']); 
				$data['sysuser_email'] = trim($_POST['sysuser_email']); 
				$data['sysuser_describe'] = trim($_POST['sysuser_describe']);
				$User->where('1=1')->save($data);
			}
			$this->success('资料修改成功！');
		}else{
			$this->error('资料修改失败!');
		}
	}
}
?>
